const XLSX = require('xlsx');
const fs = require('fs');
const path = require('path');
const axios = require('axios');
const FormData = require('form-data');
const mockDatabase = require('./src/config/mockDatabase');

async function testV2ImportFlow() {
  console.log('=== 测试V2导入完整流程 ===');
  
  try {
    // 1. 创建测试Excel文件（V2格式）
    console.log('\n1. 创建测试Excel文件...');
    const workbook = XLSX.utils.book_new();
    
    // Dishes工作表数据
    const dishesData = [
      {
        'dish_sku': 'TEST001',
        'dish_slug': 'test-burger',
        'name_zh': '测试汉堡',
        'name_en': 'Test Burger',
        'category': '主食',
        'base_status': 'active',
        'description_zh': '美味的测试汉堡',
        'description_en': 'Delicious test burger',
        'ingredients_zh': '牛肉饼,生菜,番茄',
        'ingredients_en': 'Beef patty, lettuce, tomato',
        'tags': '热门,推荐',
        'popularity': 85
      },
      {
        'dish_sku': 'TEST002',
        'dish_slug': 'test-drink',
        'name_zh': '测试饮料',
        'name_en': 'Test Drink',
        'category': '饮料',
        'base_status': 'active',
        'description_zh': '清爽的测试饮料',
        'description_en': 'Refreshing test drink',
        'ingredients_zh': '水,糖浆',
        'ingredients_en': 'Water, syrup',
        'tags': '清爽',
        'popularity': 70
      }
    ];
    
    const dishesSheet = XLSX.utils.json_to_sheet(dishesData);
    XLSX.utils.book_append_sheet(workbook, dishesSheet, 'Dishes');
    
    // Variants工作表数据
    const variantsData = [
      {
        'dish_sku': 'TEST001',
        'name_zh': '测试汉堡',
        'variant_code': 'REGULAR',
        'variant_name': '标准版',
        'price': 25.00,
        'compare_at_price': 30.00,
        'is_default': true,
        'stock': 100
      },
      {
        'dish_sku': 'TEST002',
        'name_zh': '测试饮料',
        'variant_code': 'MEDIUM',
        'variant_name': '中杯',
        'price': 8.00,
        'compare_at_price': 10.00,
        'is_default': true,
        'stock': 50
      }
    ];
    
    const variantsSheet = XLSX.utils.json_to_sheet(variantsData);
    XLSX.utils.book_append_sheet(workbook, variantsSheet, 'Variants');
    
    // Options工作表数据
    const optionsData = [
      {
        'dish_sku': 'TEST001',
        'name_zh': '测试汉堡',
        'group_code': 'SIZE',
        'group_name': '尺寸',
        'required': false,
        'value_code': 'LARGE',
        'value_name': '大份',
        'price_delta': 5.00
      }
    ];
    
    const optionsSheet = XLSX.utils.json_to_sheet(optionsData);
    XLSX.utils.book_append_sheet(workbook, optionsSheet, 'Options');
    
    // 保存Excel文件
    const testFilePath = path.join(__dirname, 'test_v2_import.xlsx');
    XLSX.writeFile(workbook, testFilePath);
    console.log(`测试文件已创建: ${testFilePath}`);
    
    // 2. 检查导入前的数据库状态
    console.log('\n2. 检查导入前的数据库状态...');
    const beforeItems = await mockDatabase.query('SELECT * FROM menu_items WHERE deleted_at IS NULL');
    console.log(`导入前菜单项数量: ${beforeItems.length}`);
    beforeItems.forEach(item => {
      console.log(`  - ID: ${item.id}, 名称: ${item.name}, 英文名: ${item.name_en}`);
    });
    
    // 3. 上传并验证文件
    console.log('\n3. 上传并验证文件...');
    const form = new FormData();
    form.append('file', fs.createReadStream(testFilePath));
    
    const validateResponse = await axios.post('http://localhost:3001/api/menu-import/v2/validate', form, {
      headers: {
        ...form.getHeaders(),
        'Authorization': 'Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyX2lkIjoxLCJ1c2VybmFtZSI6ImFkbWluIiwiZW1haWwiOiJhZG1pbkBleGFtcGxlLmNvbSIsInJvbGUiOiJhZG1pbiIsImlhdCI6MTc1NzE0MDUzOCwiZXhwIjoxNzU3MjI2OTM4fQ.HH5ZrY0tIwELZdMGWMX2RIkrx9OXIjWIcgBjG7WNhjE'
      }
    });
    
    console.log('验证响应状态:', validateResponse.status);
    console.log('验证响应数据:', JSON.stringify(validateResponse.data, null, 2));
    
    if (!validateResponse.data.success) {
      console.error('文件验证失败!');
      return;
    }
    
    // 4. 等待验证完成
    console.log('\n4. 等待验证完成...');
    const jobId = validateResponse.data.job_id;
    let jobStatus;
    let attempts = 0;
    const maxAttempts = 10;
    
    do {
      await new Promise(resolve => setTimeout(resolve, 2000)); // 等待2秒
      attempts++;
      
      const statusResponse = await axios.get(`http://localhost:3001/api/menu-import/v2/jobs/${jobId}`, {
        headers: {
          'Authorization': 'Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyX2lkIjoxLCJ1c2VybmFtZSI6ImFkbWluIiwiZW1haWwiOiJhZG1pbkBleGFtcGxlLmNvbSIsInJvbGUiOiJhZG1pbiIsImlhdCI6MTc1NzE0MDUzOCwiZXhwIjoxNzU3MjI2OTM4fQ.HH5ZrY0tIwELZdMGWMX2RIkrx9OXIjWIcgBjG7WNhjE'
        }
      });
      
      jobStatus = statusResponse.data.status;
      console.log(`验证状态 (${attempts}/${maxAttempts}): ${jobStatus}`);
      
    } while (jobStatus === 'validating' && attempts < maxAttempts);
    
    if (jobStatus !== 'validated') {
      throw new Error(`验证未完成，最终状态: ${jobStatus}`);
    }

    // 5. 提交导入
    console.log('\n5. 提交导入...');
    const commitResponse = await axios.post(`http://localhost:3001/api/menu-import/v2/commit?job_id=${jobId}`, {}, {
      headers: {
        'Authorization': 'Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyX2lkIjoxLCJ1c2VybmFtZSI6ImFkbWluIiwiZW1haWwiOiJhZG1pbkBleGFtcGxlLmNvbSIsInJvbGUiOiJhZG1pbiIsImlhdCI6MTc1NzE0MDUzOCwiZXhwIjoxNzU3MjI2OTM4fQ.HH5ZrY0tIwELZdMGWMX2RIkrx9OXIjWIcgBjG7WNhjE'
      }
    });
    
    console.log('提交响应状态:', commitResponse.status);
    console.log('提交响应数据:', JSON.stringify(commitResponse.data, null, 2));
    
    // 6. 检查导入后的数据库状态
    console.log('\n6. 检查导入后的数据库状态...');
    // 等待一下确保数据已写入
    await new Promise(resolve => setTimeout(resolve, 1000));
    
    const afterItems = await mockDatabase.query('SELECT * FROM menu_items WHERE deleted_at IS NULL');
    console.log(`导入后菜单项数量: ${afterItems.length}`);
    afterItems.forEach(item => {
      console.log(`  - ID: ${item.id}, 名称: ${item.name}, 英文名: ${item.name_en}, 规范化名称: ${item.normalized_name}`);
    });
    
    const newItems = afterItems.filter(item => !beforeItems.find(before => before.id === item.id));
    console.log(`\n新增菜单项数量: ${newItems.length}`);
    newItems.forEach(item => {
      console.log(`  - 新增: ID: ${item.id}, 名称: ${item.name}, 英文名: ${item.name_en}`);
    });
    
    // 6. 检查分类数据
    const categories = await mockDatabase.query('SELECT * FROM menu_categories WHERE deleted_at IS NULL');
    console.log(`\n分类数量: ${categories.length}`);
    categories.forEach(cat => {
      console.log(`  - ID: ${cat.id}, 名称: ${cat.name}`);
    });
    
    // 清理测试文件
    fs.unlinkSync(testFilePath);
    console.log('\n测试文件已清理');
    
  } catch (error) {
    console.error('测试过程中出错:', error.message);
    if (error.response) {
      console.error('响应状态:', error.response.status);
      console.error('响应数据:', error.response.data);
    }
  }
}

testV2ImportFlow();